package dynamicFile

import (
	"fmt"
	"meetroom/dataHandle"
	"meetroom/err"
	"meetroom/server/manage"
	"net/http"
	"os"
	"path"
	"path/filepath"

	"github.com/garyburd/redigo/redis"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
)

func newController() manage.Viewer {
	v := manage.QuickNewViewer("/*path", nil, nil,
		manage.NewHandle(manage.GET, func(d *gorm.DB, c *redis.Conn) gin.HandlerFunc {
			return func(c *gin.Context) {
				p := c.Param("path")

				filePath, _ := filepath.Abs(path.Join(dynamicPath, p))
				
				if exists(filePath){
					c.File(filePath)
				}else {
					c.JSON(http.StatusNotFound,dataHandle.FailureFuncResult(err.NotFoundAPI,
						fmt.Sprintf("file `%s`",p)))
				}
				c.Abort()
			}
		}))

	return v
}
func exists(name string) bool {
    if _, err := os.Stat(name); err != nil {
        if os.IsNotExist(err) {
            return false
        }
    }
    return true
}